package com.example.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;


/**
 * 区划表
 * region
 */
@Data
@Accessors(chain = true)
@TableName(value = "region")
public class Region implements Serializable {
    /**
     * 区划代码
     */
    @TableId
    private String id;

    /**
     * 父级代码
     */
    private String pid;

    /**
     * 区划名称
     */
    private String value;

//    /**
//     * 对应链接查子页面用
//     */
//    private String url;
//    /**
//     * 行政级别
//     */
//    private Integer level;
//    /**
//     * 处理标记
//     */
//    private boolean flag;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;
    public static final String ROOT_URL = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2022/";

    public static Region trans(Element element, String pid, int level) {
        Elements as = element.select("a");
        String id, href, text;
        if (level < 4) {
            if (as.isEmpty()) {
                //市辖区
                Elements tds = element.select("td");
                id = tds.get(0).text();
                href = null;
                text = tds.get(1).text();
            } else {
                //非市辖区
                id = as.get(0).text();
                href = as.get(0).attr("href");
                text = as.get(1).text();
            }
        } else {
            //村 取第三个标签的innerHTML
            Elements tds = element.select("td");
            id = tds.get(0).text();
            href = tds.get(0).attr("href");
            text = tds.get(2).text();
        }
        id = StringUtils.trimTrailingCharacter(id, '0');
//        return new Region().setId(id).setPid(pid).setUrl(href).setValue(text).setLevel(level + 1);
        return new Region().setId(id).setPid(pid).setValue(text);
    }


    public static Elements select(String url) throws IOException {
        return Jsoup.connect(url).get().select("tr[class*=tr]");
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Region region = (Region) o;
        return Objects.equals(id, region.id) && Objects.equals(pid, region.pid);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, pid);
    }
}